package com.leyou.auth.interceptors;

import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetails;
import com.leyou.auth.local.UserContext;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.leyou.auth.constants.JwtConstants.COOKIE_NAME;

@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private JwtUtils jwtUtils;

    public LoginInterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从cookie中获取jwt
        String jwt = CookieUtils.getCookieValue(request, COOKIE_NAME);
        //判断是否为空
        if (StringUtils.isBlank(jwt)) {
            //未登录
            throw new LyException(401, "未登录！");
        }
        //获取payload
        Payload payload = jwtUtils.parseJwt(jwt);
        //获取user
        UserDetails user = payload.getUserDetails();
        //判断是否为空
        if (user == null) {
            //未登录
            throw new LyException(401, "未登录！!");
        }
        //向threadLocal中添加数据
        UserContext.setUser(user);
        UserContext.setJwtTl(jwt);
        log.info("用户{}正在访问。", user.getUsername());
        return true;
    }

//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//
//    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //将threadLocal中数据移除
        UserContext.removeUser();
    }
}
